package com.example.leonard.service.impl;

import com.example.leonard.service.RateLimitService;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @auther heyang
 * @date 2021/8/29 16:56
 */
@Service
public class RateLimitServiceImpl implements RateLimitService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional
    public void rateLimit(String ipAddr, String value) {
        String redisKey = ipAddr + "_" + value;
        int count = 0;
        try {
            /**
             * 判断key 是否过期 key过期 则
             */
            if (!redisTemplate.hasKey(redisKey)) {

                redisTemplate.opsForValue().set(redisKey,0, 120, TimeUnit.SECONDS);
            }

            Long expire = redisTemplate.opsForValue().getOperations().getExpire(redisKey);
            System.out.println("rediskey的过期时间" + expire);

            redisTemplate.opsForValue().increment(redisKey,1);
            count = (int) redisTemplate.opsForValue().get(redisKey);
            System.out.println(count);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("redis异常");
        }
        if (count > 5) {
            throw new RuntimeException("访问频繁了,客官!");
        }
    }
}
